package com.lottery.game.runner.v2;

import com.alibaba.fastjson.JSON;
import com.lottery.game.common.constants.GameConstants;
import com.lottery.game.common.utils.UUIDUtils;
import com.lottery.game.core.modules.entity.game.GameRoom;
import com.lottery.game.core.modules.entity.user.ChatRecord;
import com.lottery.game.core.modules.entity.user.WebsocketMessage;
import com.lottery.game.core.modules.service.app.OnlineAppContext;
import com.lottery.game.core.modules.service.app.WebSocketService;
import com.lottery.game.core.modules.service.app.WebsocketMessageService;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import lombok.extern.slf4j.Slf4j;

/**
 * instead of com.runshang.apps.cloudgame.runner.PushMsgThread
 * @author Jake
 *
 */
@Slf4j
public class GamblingClosuresExecutor implements Runnable {

	private List<GameRoom> roomList;

	private String msg;

	private WebSocketService webSocketService;

	private OnlineAppContext context;

	private WebsocketMessageService websocketMessageService;

	private Integer gameStatus;

	private boolean inited = false;

	private GamblingClosuresExecutor() {}

	public GamblingClosuresExecutor(WebSocketService webSocketService, OnlineAppContext context) {
		this();
		this.webSocketService = webSocketService;
		this.context = context;
	}

	public void initParams(List<GameRoom> roomList, String msg) {
		this.roomList = roomList;
		this.msg = msg;
		this.inited = true;
	}

	public void initParams(List<GameRoom> roomList, String msg, WebsocketMessageService websocketMessageService, Integer gameStatus) {
		this.roomList = roomList;
		this.msg = msg;
		this.gameStatus = gameStatus;
		this.inited = true;
		this.websocketMessageService = websocketMessageService;
	}

	public WebSocketService getWebSocketService() {
		return this.webSocketService;
	}

	@Override
	public void run() {
		if (inited) {
			Assert.notNull(getWebSocketService(), "webSocketService could not be null");

			if(!CollectionUtils.isEmpty(roomList)) {
				String senderNickname = GameConstants.SENDER_SYSTEM;
				String chatType = GameConstants.CHATTYPE_SYSTEM_MSG;
				ChatRecord chatRecord = new ChatRecord();
				chatRecord.setSendernickname(senderNickname);
				chatRecord.setChatType(chatType);
				chatRecord.setMsgContent(msg);
				String sendMsg = JSON.toJSONString(chatRecord);

				roomList.forEach(room -> {
					String roomNumber = room.getRoomnumber();
					//String chatId = this.getChatId(chatType,roomNumber);
					Set<String> userIdList = context.getUserIdsByRoomNumber(roomNumber);
					
					if (!CollectionUtils.isEmpty(userIdList)) {
						userIdList.forEach(userId -> {
							if (gameStatus != null) {
								this.send(websocketMessageService.saveWebsocketMessage2(senderNickname, sendMsg, userId, roomNumber, chatType, gameStatus, GameConstants.WEBSOCKET_MESSAGE_STATUS_CREATE));
							}
							//存到定时任务发送
							// webSocketService.sendToTheUser(sendMsg, userId, roomNumber);
						});
					}
				});
			}
		} else {
			log.error("Please init the params by triggering the initParams method");
		}
	}
	
	private void send(WebsocketMessage message){
		Map<String,String> sendMsgMap = new HashMap<>();
		String source = message.getSenderNickname();
		/*String sendMsg = message.getSendMsg();
		String roomNumber = message.getRoomNumber();
		String chatType = message.getChatType();*/

		//String currentServerKey = "WSCONNECT_" + serverPort + "_";

		//Set<String> wsConnected = redisFeignClient.keys(currentServerKey + "*");

		/*Set<String> userIds = wsConnected.stream()
				.map(mapper-> mapper.replace(currentServerKey, ""))
				.collect(Collectors.toSet());*/
		sendMsgMap.put("message_id", message.getId());
		sendMsgMap.put("sendMsg", message.getSendMsg());
		if(GameConstants.SENDER_SYSTEM.equals(source)) {
			//满足这个通道的才发
			//if(userIds.contains(wm.getUserId())) {
				 webSocketService.sendToTheUser(JSON.toJSONString(sendMsgMap), message.getUserId(), null,null);
			//}
		} else {
		//	if(userIds.contains(wm.getUserId())) {
				webSocketService.sendToTheUser(JSON.toJSONString(sendMsgMap), message.getUserId(), null,null);
		//	}
		}
	}

	public void execute() {
		if (this != null) {
			ExecutorService exec = Executors.newCachedThreadPool();
			exec.execute(this);
		}
	}

}
